import _ from 'lodash'
import { ipcMain, Event } from 'electron'
import fs from 'fs';
import IElectronModule from './bg_base';
import { IpcReturnStatus, IpcReturnValue } from '@/plugin/ipc_renderer_ex';

/** 打开文件对话框 */
export const TEST_FILE_GET = "test-file-get";
const TEST_FILE_GET_RET = "test-file-get-ret";


// 定义ipc接口
declare module '@/plugin/ipc_renderer_ex' {
    interface IpcSendTypes {
        [TEST_FILE_GET]: IpcSendTypeNode<IpcTestFileGetOption, IpcReturnValue<{ name: string, is_dir: boolean }[]>>
    }
}

export interface IpcTestFileGetOption {
    /** 要获取的文件路径 */
    path: string;
}

/**
 * 文件处理
 */
class TestFile implements IElectronModule {

    install(win: Electron.BrowserWindow): void {
        ipcMain.on(TEST_FILE_GET, this.fileGet.bind(this));
    }

    private async fileGet(
        event: Event,
        { path = "d:/" }: IpcTestFileGetOption
    ) {

        //let path = _.get(arg, "path", "d:/");
        let files = fs.readdirSync(path);
        let f_is_dir = (fname: string) => {
            try {
                let fstat = fs.statSync(path + fname);
                return fstat.isDirectory();
            }
            catch (ex) { return false; }
        };
        let ret = _.map(files, f => ({
            name: f,
            is_dir: f_is_dir(f)
        }))
        //let files = fs.readdirSync(path);
        //event.returnValue = { items: ret };

        event.sender.send(TEST_FILE_GET_RET, {
            status: IpcReturnStatus.success,
            message: "成功获取文件列表",
            value: ret
        } as IpcReturnValue<{ name: string, is_dir: boolean }[]>);
    }
}

export default new TestFile();
